jsPlumb.ready(jsPlumbMain);
//所有节点位置集合
var dragNodeMap = new Map();
//移动时鼠标在的节点
var mainNodeID = "";
var multiMove = false;
// 主要入口
function jsPlumbMain() {
    //定义可拖拽控件
    $('.jnode-box').draggable({
        helper: 'clone',
        scope: 'ss'
    });

    //添加连接后事件
    jsPlumb.bind("connection", function(connInfo, originalEvent) {
        //originalEvent为鼠标连接触发事件
        if (originalEvent) {
            addTransition(connInfo);
            connInfo.connection.id = getNewGuid();
            //给connect的svg增加id属性
            jsPlumb.setAttribute(connInfo.connection.canvas, "id", connInfo.connection.id)
        }
    });

    //点击连接事件
    jsPlumb.bind('click', (connection, originalEvent) => {
        //锚点点击不操作
        if (!connection.type) {
            //取消所有连线的高亮颜色
            cacneConnectLightSelect();
            cancelNodeLightSelect();
            //设置当前连接线高亮
            connection.setPaintStyle({ lineWidth: 5, strokeStyle: "#5FB878" })
            //增加标记
            jsPlumb.setAttribute(connection.canvas, "select", "2")
        }
    })

    //添加连接前判断
    jsPlumb.bind('beforeDrop', function(connection) {
        var startActivityType = $("#" + connection.sourceId).attr('jnode');
        var endActivityType = $("#" + connection.targetId).attr('jnode');
        var result = true;
        if (connection.sourceId == connection.targetId) {
            //开始与结束活动不能是同一个
            result = false;
        } else if (startActivityType == "end" || endActivityType == "start") {
            //起点不能是结束，重点不能是开始
            result = false;
        }
        else {
            result = checkTransition(connection);
        }
        if (!result) {
            //删除连接不成功生成的无用断点
            jsPlumb.deleteEndpoint(connection.dropEndpoint)
        }
        return result
    })
}

//取消连接高亮
function cacneConnectLightSelect() {
    //去除标记
    var connects = jsPlumb.getAllConnections();
    for (var i = 0; i < connects.length; i++) {
        var connect = connects[i];
        jsPlumb.setAttribute(connect.canvas, "select", "1")
    }
    jsPlumb.select().setPaintStyle({ lineWidth: 5, strokeStyle: "#456" })
}

//取消节点高亮显示
function cancelNodeLightSelect() {
    $(".bdc-primary").removeClass("bdc-primary-select");
}

//开始整体拖动
function startMultiMove(){
    multiMove = true;
}

//关闭整体拖动
function closeMultiMove(){
    multiMove = false;
}

//注册可拖动（添加）
function addDraggable(id) {
    if (!dragNodeMap.has(id)) {
        dragNodeMap.set(id, {
            id: id,
            left: parseInt($("#" + id).css("left"), 10),
            top: parseInt($("#" + id).css("top"), 10)
        })
    }
    jsPlumb.draggable(id, {
        containment: 'parent',
        grid: [8, 8],
        start: function(event, ui) {
            if(multiMove){
                var nodeID = $(ui.helper.context).attr("id");
                if (mainNodeID == "") {
                    mainNodeID = nodeID;
                }
            }
        },
        drag: function(event, ui) {
            if(multiMove){
                var nodeID = $(ui.helper.context).attr("id");
                if (mainNodeID == nodeID) {
                    var moveX = ui.position.left - dragNodeMap.get(nodeID).left
                    var moveY = ui.position.top - dragNodeMap.get(nodeID).top;
                    multiDarg(moveX, moveY);
                }
            }
        },
        stop: function(event, ui) {
            if(multiMove){
                var nodeID = $(ui.helper.context).attr("id");
                moveActivity(nodeID, ui.position.left, ui.position.top);
                if (mainNodeID == nodeID) {
                    mainNodeID = "";
                }
            }
            dragNodeMap.forEach(function(value, key) {
                value.left =parseInt($("#" + key).css("left"), 10);
                value.top =parseInt($("#" + key).css("top"), 10);
            });
         
        }
    });
}

//多节点拖动
function multiDarg(moveX, moveY) {
    dragNodeMap.forEach(function(value, key) {
        if (key != mainNodeID) {
            $("#" + key).css("left", value.left + moveX);
            $("#" + key).css("top", value.top + moveY);
            jsPlumb.repaintEverything();
        }
    });
}

//注册可拖动（设置）
function registDraggable(id) {
    jsPlumb.getInstance({}).setDraggable(document.getElementById(id), true);
}

//取消可拖动
function cancelDraggable(id) {
    jsPlumb.getInstance({}).setDraggable(document.getElementById(id), false);
}

// 注册自动连接
function registAutoConnect(id) {
    jsPlumb.makeSource(id, {
        endpoint: "Dot",
        anchor: "Continuous"
    })

    jsPlumb.makeTarget(id, {
        endpoint: "Dot",
        anchor: "Continuous"
    })
}

//取消所有自动连接
function cancelAllAutoConnect() {
    jsPlumb.unmakeEverySource()
    jsPlumb.unmakeEveryTarget()
}

//删除节点与连接
function deleteNodeAndConnect(id) {
    jsPlumb.remove(id)
}

//增加连接
function addConnect(id, sourceID, targetID) {
    var connection = jsPlumb.connect(
    {
        source: sourceID,
        target: targetID
    });
    connection.id = id
    //给connect的svg增加id属性
    jsPlumb.setAttribute(connection.canvas, "id", connection.id)
}

//删除连接
function deleteConnect(id) {
    var connects = jsPlumb.getAllConnections();
    for (var i = 0; i < connects.length; i++) {
        var connect = connects[i];
        if (connect.id == id) {
            jsPlumb.detach(connect)
        }
    }
}

//生成uuid
function getNewGuid() {
    var date = new Date();
    var dateGuid = convertDateToString(date);
    var randomGuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    })
    return dateGuid + randomGuid.substring(0, 36);
}

function convertDateToString(now) {
    var year = now.getFullYear();
    var month = (now.getMonth() + 1).toString();
    var day = (now.getDate()).toString();
    var hour = (now.getHours()).toString();
    var minute = (now.getMinutes()).toString();
    var second = (now.getSeconds()).toString();
    if (month.length == 1) {
        month = "0" + month;
    }
    if (day.length == 1) {
        day = "0" + day;
    }
    if (hour.length == 1) {
        hour = "0" + hour;
    }
    if (minute.length == 1) {
        minute = "0" + minute;
    }
    if (second.length == 1) {
        second = "0" + second;
    }
    var dateTime = year + month + day + hour + minute + second;
    return dateTime;
}